package com.jike.jkgame.data;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;

import com.jike.jkgame.Utilis;
import com.jike.jkgame.db.ResourcesDAO;

public class Fragment {
	public int id;
	public String name;
	public String description;
	
	private static Fragment parseFragment(DataInputStream dis, byte[] buff) {
		Fragment fragment = new Fragment();
		
		try {
			fragment.id = dis.readInt();
			fragment.name = Utilis.getString(dis, buff);
			fragment.description = Utilis.getString(dis, buff);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		
		return fragment;
	}
	
	public static int parseDataFile(InputStream in) {
		DataInputStream dis = new DataInputStream(in);
		int count  = 0;
		
		ResourcesDAO dao = ResourcesDAO.get();
		byte[] buff = new byte[4096];
		
		try {
			int type = dis.readInt();
			int version = dis.readInt();
			
			int myVersion = dao.getDataFileVersion(type);
			
			if (myVersion >= version) {
				return 0;
			}
			
			dao.clearFragments();
			Fragment f = null;
			do {
				f = parseFragment(dis, buff);
				dao.insertFragment(f);
				count++;
			}while(f != null);
			dao.updateDataFileVersion(type, version);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return count;
		
	}
}
